package com.ding.commander;

import com.ding.common.Repeater;
import com.ding.common.Threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

//服务监听器
class ServerAccepter {

    private static Logger logger = Logger.getLogger("");

    private int serverListenerPort;

    private ServerSocket serverSocket;

    private CPool pool;

    void setPool(CPool pool) {
        this.pool = pool;
    }

    void setServerListenerPort(int serverListenerPort) {
        this.serverListenerPort = serverListenerPort;
    }

    void start() throws IOException {
        this.serverSocket = new ServerSocket(this.serverListenerPort);

        Threads.exe(() -> {

            logger.info("开始监听服务");

            while (true) {

                try {

                    //收到一个连接请求
                    Socket accept = serverSocket.accept();

                    System.out.println("收到请求");
                    //交给其他线程处理以防阻塞
                    Threads.exe(() -> {

                        System.out.println("获取中继器");

                        Repeater repeater = pool.get();

                        if (repeater == null) {
                            System.out.println("获取失败");
                            try {
                                accept.close();
                                logger.warning("服务|未获取到中继器|关闭");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return;
                        }

                        System.out.println("获取到中继器");

                        try {
                            repeater.getLeft().setSocket(accept);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                        repeater.startLeftToRight();

                        System.out.println("开始由左侧向右侧复制");

                    });


                } catch (IOException e) {
                    break;
                }
            }

        });

    }


}
